<?php
/**
 * Description: 往期公开课跳转
 * User: devforma
 * Date: 15/6/23
 * Time: 11:23
 */

require_once LIB_DIR . '/LiveCourse.class.php';
class StaticOpenCourse implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb, $cmsdb;

        if (empty($queryArgs['user_id']) || !is_numeric($queryArgs['user_id']) 
            || empty($queryArgs['class_id']) || !preg_match('/^\w+$/', trim($queryArgs['class_id']))
        ) {
            die('非法请求');
        }

        $nickname = $uddb->getVar('SELECT `nickname` FROM `user_social_info` WHERE `user_id`='.$queryArgs['user_id']);
        if (empty($nickname))
            $nickname = 'student_'.$queryArgs['user_id'];

        $sql = 'SELECT `start_time`, `room_id`, `lector_id` FROM `data_live_class` WHERE `id`='.$queryArgs['class_id'];
        $class = $cmsdb->getRow($sql);
        LiveCourse::logEnter($queryArgs['user_id'], $queryArgs['class_id'], 'mobile_web', explode(' ', $class->start_time)[0], 1);

        $courseId = $cmsdb->getVar('SELECT c.id FROM `data_live_course` AS c INNER JOIN `relationship_live_class_and_course` AS r
        ON c.id=r.course_id AND r.class_id=:cid AND c.type_id=1 LIMIT 1', array(':cid' => $queryArgs['class_id']));

        $this->enterClass($queryArgs['user_id'], $courseId, $queryArgs['class_id'], $class->lector_id, true);

        $redirectUrl = $this->getLiveClassUrl($queryArgs['user_id'], $nickname, $class->room_id, true);

        header('Location: ' . $redirectUrl);
    }

    /**
     * 用户观看记录
     *
     * @param $userId
     * @param $courseId
     * @param $classId
     * @param $lectorId
     * @param $isOpen
     */
    private function enterClass($userId, $courseId, $classId, $lectorId, $isOpen) {
        global $cmsdb;

        $exists = $cmsdb->getVar('SELECT `id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `class_id`=:cid LIMIT 1',
            array(':uid' => $userId, ':cid' => $classId));

        if (empty($exists)) {
            $cmsdb->insert('data_liveclass_grade', array(
                'course_id' => $courseId,
                'class_id' => $classId,
                'lector_id' => $lectorId,
                'user_id' => $userId,
                'grade_score' => 0,
                'is_openclass' => $isOpen,
                'enter_time' => date('Y-m-d H:i:s'),
                'comment' => ''
            ));
        }
    }

    /**
     * 获取直播课播放地址
     * @param int $uid 用户id
     * @param string $nickname 昵称
     * @param string $roomId 房间id
     * @param bool $isH5 是否为H5
     * @return string
     */
    private function getLiveClassUrl($uid, $nickname, $roomId, $isH5 = false) {
        if ($isH5) {
            $api = "http://api.duobeiyun.com/api/v3/room/enter?";
        } else {
            $api = "http://api.jiangzuotong.com/api/v2/room/enter?";
        }

        $params = array(
            'nickname' => trim($nickname),
            'partner' => '20140807101355',
            'roomId' => $roomId,
            'timestamp' => time() * 1000,
            'uid' => $uid,
            'userRole' => 2 //2为学生上课地址
        );


        /*****************************************************
         * 生成签名
         */
        ksort($params);

        $paramStr = '';

        foreach($params as $param_key => $param_value) {
            $paramStr .= (strval($param_key).'='.strval($param_value).'&');
        }
        $sign = md5(rtrim($paramStr, '&').'771f3c17303c49f6a8dc3e3ffbf41990');


        /*****************************************************
         * 构造播放地址
         */
        $paramStr = '';

        foreach($params as $param_key => $param_value) {
            $paramStr .= (strval($param_key).'='.urlencode(strval($param_value)).'&');
        }

        $paramStr .= ('sign='.$sign);

        return $api.$paramStr;
    }
}
